package com.rent.auth.pojo;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.rent.auth.model.Admin;
import com.rent.auth.model.RolePermission;
import com.rent.common.utils.DateUtil;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author zhang
 * @create 2022/9/13 9:58
 */
@JsonIgnoreProperties(ignoreUnknown = true)
@Setter
@Getter
@NoArgsConstructor
public class AdminUserDetails implements UserDetails {

    /**
     * 用户信息
     */
    private Admin admin;

    /**
     * 用户角色列表
     */
    private List<RolePermission> permissionList;

    public AdminUserDetails(Admin admin, List<RolePermission> permissionList) {
        this.admin = admin;
        this.permissionList = permissionList;
    }


    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (CollectionUtils.isEmpty(permissionList)) return this.getAuthorities();
        return permissionList.stream()
                .map(role -> new SimpleGrantedAuthority(role.getUri()))
                .collect(Collectors.toList());
    }

    @Override
    public String getPassword() {
        return admin.getPassword();
    }

    @Override
    public String getUsername() {
        return admin.getUsername();
    }

    // 核验账户是否过期
    @Override
    public boolean isAccountNonExpired() {
        return admin.getValidityTime() == null || DateUtil.compareToDate(admin.getValidityTime());
    }

    // 核验账户冻结状态
    @Override
    public boolean isAccountNonLocked() {
        return admin.getStatus() != null && admin.getStatus() == 1;
    }

    @Override
    public boolean isEnabled() {
        return admin.getStatus() != null && admin.getStatus() == 1;
    }

    // 核验密码是否过期
    @Override
    public boolean isCredentialsNonExpired() {
        return false;
    }


}
